import React, { Component } from "react";
import "./index.css";
//导入封装后的 axios 对象
import axios from "../../http/axios";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";

export default class Website extends Component {
    state = {
        //新增的表单数据
        title: "",
        url: "",
        keywords: "",
        //列表数据
        data: [],
        //搜索关键字
        gjz: "",
        //关于更新的状态
        hasDBClick: false, //是否双击
        dbId: null, //双击网址的 id
        //是否新增
        isAdd: false 
    };

    render() {
        //解构赋值
        let { title, url, keywords, hasDBClick, dbId } = this.state;
        return (
            <div className="website-container">
                <div className="title"><h2>网站管理</h2>  <button onClick={this.add}>新增网站</button></div>
                <ToastContainer />
                {this.state.isAdd && <div>
                    <hr />
                    <div className="form">
                        <label>
                            网站名称:{" "}
                            <input
                                type="text"
                                value={title}
                                onChange={this.saveData}
                                name="title"
                            />
                        </label>
                        <label>
                            网址:{" "}
                            <input
                                type="text"
                                value={url}
                                onChange={this.saveData}
                                name="url"
                            />
                        </label>
                        <label>
                            关键字:{" "}
                            <input
                                type="text"
                                value={keywords}
                                onChange={this.saveData}
                                name="keywords"
                            />
                        </label>
                        <button onClick={this.save}>新增网址</button>
                    </div>
                </div>}
                <hr />
                <div className="search">
                    <input
                        type="text"
                        name="gjz"
                        value={this.state.gjz}
                        onChange={this.saveData}
                    />
                    &nbsp;<button onClick={this.search}>搜索</button>
                </div>
                <hr />
                <table border="1">
                    <thead>
                        <tr>
                            <td>ID</td>
                            <td>网站名称</td>
                            <td>网址</td>
                            <td>关键字</td>
                            <td>操作</td>
                        </tr>
                    </thead>
                    <tbody>
                        {this.state.data.map((item) => {
                            return (
                                <tr key={item.id}>
                                    <td>{item.id}</td>
                                    <td>
                                        <a
                                            rel="noreferrer"
                                            target="_blank"
                                            href={item.url}
                                        >
                                            {item.title}
                                        </a>
                                    </td>
                                    <td
                                        onDoubleClick={this.doubleClick(
                                            item.id
                                        )}
                                    >
                                        {hasDBClick && item.id === dbId ? (
                                            <input
                                                type="text"
                                                value={item.url}
                                                autoFocus
                                                onBlur={this.blur(item.id)}
                                                onChange={this.change(item.id)}
                                            />
                                        ) : (
                                            item.url
                                        )}
                                    </td>
                                    <td>{(item.keyword instanceof Array) && item.keywords.join(", ")}</td>
                                    <td>
                                        <button onClick={this.del(item.id)}>
                                            点击删除
                                        </button>
                                    </td>
                                </tr>
                            );
                        })}
                        {this.state.data.length === 0 && (
                            <tr>
                                <td colSpan="5" style={{ textAlign: "center" }}>
                                    暂无数据
                                </td>
                            </tr>
                        )}
                    </tbody>
                </table>
            </div>
        );
    }

    //点击显示新增表单
    add = () => {
        this.setState({
            isAdd: !this.state.isAdd
        })
    }

    //绑定丧失焦点事件, 更新数据
    blur = (id) => {
        return async (e) => {
            // console.log(id, e.target.value);
            //修改状态
            this.setState({
                hasDBClick: false,
                dbId: null,
            });

            await axios({
                method: "patch",
                url: "/website/" + id,
                //请求体
                data: {
                    url: e.target.value,
                },
            });
            //如果成功 提示添加成功
            toast.success("更新成功!", {
                position: toast.POSITION.TOP_CENTER,
            });
        };
    };

    //修改更新 input 输入框的值
    change = (id) => {
        return (e) => {
            //e.target.value
            this.setState({
                data: this.state.data.map((item) => {
                    //如果当前网址的 id 与正在更新的 id 相同
                    if (item.id === id) {
                        item.url = e.target.value;
                    }
                    return item;
                }),
            });
        };
    };

    //双击更新功能
    doubleClick = (id) => {
        return () => {
            this.setState({
                hasDBClick: true,
                dbId: id,
            });
        };
    };

    //搜索功能
    search = async () => {
        //获取关键字   http://127.0.0.1:3001/website?q=关键字
        let gjz = this.state.gjz;
        let result = await axios("/website", {
            //设置查询字符串参数的
            params: {
                q: gjz,
            },
        });

        //更新数据
        this.setState({
            data: result,
        });
    };

    //保存表单数据
    saveData = (e) => {
        this.setState({
            [e.target.name]: e.target.value,
        });
    };

    //新增网址
    save = async () => {
        let { title, url, keywords } = this.state;
        //获取数据
        let data = {
            title,
            url,
            keywords: keywords.split(",").map((item) => item.trim()), //清除空格
        };
        //发送 AJAX 请求
        let result = await axios.post("/website", data);
        //如果成功 提示添加成功
        toast.success("添加成功!", {
            position: toast.POSITION.TOP_CENTER,
        });
        //清空表单数据
        this.setState({
            title: "",
            url: "",
            keywords: "",
            data: [...this.state.data, result], //更新
        });
        
    };

    //删除网址 delete   /website/7
    del = (id) => {
        return async () => {
            //用户确认
            if (!window.confirm("您确定要删除么???")) return;

            await axios.delete("/website/" + id); //params 参数    query参数 /search?keyword=zhangsan
            //更新 state 中 data
            this.setState({
                //过滤  将 id 不等于要删除 id 的网址留下
                data: this.state.data.filter((item) => item.id !== id),
            });
            toast.success("删除成功!", {
                position: toast.POSITION.TOP_CENTER,
            });
        };
    };

    //组件挂载完毕
    async componentDidMount() {
        let data = await axios("/website");
        //如果请求成功, 则保存网站数据到 state
        this.setState({
            data: data,
        });
    }
}
